package com.miracle9.game.dao;
import com.miracle9.game.bean.Pager;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

@Repository
public class Dao
{
  @Autowired
  private SessionFactory sessionFactory;
  protected Session getSession()
  {
    return this.sessionFactory.getCurrentSession();
  }
  
  public Pager getQuantity(String sql, Pager pager, Object... params)
  {
    Assert.hasText(sql, "hql不能为空");
    Query countQuery = getSession().createSQLQuery(
      "select count(*) from (" + sql + ") t");
    if (StringUtils.isNotBlank(pager.getOrderBy())) {
      sql = sql + " order by " + pager.getOrderBy();
    }
    if (StringUtils.isNotBlank(pager.getOrder())) {
      sql = sql + " " + pager.getOrder();
    }
    SQLQuery query = getSession().createSQLQuery(sql);
    query.setFirstResult((pager.getPageNumber() - 1) * pager.getPageSize());
    query.setMaxResults(pager.getPageSize());
    if (params != null) {
      for (int i = 0; i < params.length; i++)
      {
        query.setParameter(i, params[i]);
        countQuery.setParameter(i, params[i]);
      }
    }
    pager.setTotalCount(Integer.parseInt(countQuery.uniqueResult().toString()));
    pager.setList(query.list().toArray());
    return pager;
  }
  
  public Query executeQueryHQL(String hql, Object... params)
  {
    Assert.hasText(hql, "queryString不能为空");
    Query query = getSession().createQuery(hql);
    if (params != null) {
      for (int i = 0; i < params.length; i++) {
        query.setParameter(i, params[i]);
      }
    }
    return query;
  }
  
  public SQLQuery executeSQLQuerySQL(String sql, Object... params)
  {
    Assert.hasText(sql, "queryString不能为空");
    SQLQuery query = getSession().createSQLQuery(sql);
    if (params != null) {
      for (int i = 0; i < params.length; i++) {
        query.setParameter(i, params[i]);
      }
    }
    return query;
  }
}
